<?php

namespace App\Common\ElasticSearch;

use App\Common\Utill\ElasticSearch;
use Illuminate\Support\Facades\Log;

/**
 * Class Users
 * im发送日志记录表
 *
 * @package App\Common\ElasticSearch
 *
 */
class ImSendLog
{

    /**
     * 创建im发送消息日志索引
     *
     * @param string $indexName
     *
     * @return array
     * @throws \Exception
     *
     */
    public static function create_index(string $indexName, int $shards = 1, int $replicas = 1, bool $isSql = false)
    {
        $mappings = [
            "user_id"         => ["type" => "long"],
            "account"         => ["type" => "keyword"],
            "type"            => ["type" => "keyword"],
            "group_chat_id"   => ["type" => "keyword"],
            "custom_group"    => ["type" => "keyword"],
            "request_content" => ["type" => "text"],
            "result_code"     => ["type" => "long"],
            "result_content"  => ["type" => "text"],
            "is_del"          => ["type" => "keyword"],
            "created_at"      => [
                "type"   => "date",
                "format" => "yyyy-MM-dd HH:mm:ss",
                "fields" => [
                    "keyword" => [
                        "type" => "keyword"
                    ]
                ]
            ]
        ];
        $settings = [];
        if (!$indexName) {
            $indexName = "im_record_" . date("Y-m");
        }
        $res = (ElasticSearch::instance())->settings($settings, $shards, $replicas)
                                  ->mappings($mappings)
                                  ->isSql($isSql)
                                  ->createIndex($indexName);
        if (!empty($res['acknowledged']) && !empty($res['index'])) {
            $resData['code'] = 200;
            $resData['msg']  = $res['index'] . "创建成功";
            return $resData;
        }
        $resData['code'] = $res['status'] ?? 500;
        $resData['msg']  = $indexName . "创建失败。原因：" . $res['error']['reason'] ?? "";
        return $resData;
    }

    /**
     * 写入
     *
     * @param array  $params
     * @param bool   $isSql
     * @param string $index
     *
     * @return array
     * @throws \Exception
     */
    public static function insert(array $params, string $index = "", bool $isSql = false)
    {
        $insertInfo = [
            "user_id"         => (int)($params["user_id"] ?? 0),
            "account"         => (string)($params['account'] ?? ""),
            "type"            => (int)($params['type'] ?? 1),
            "group_chat_id"   => (int)($params['group_chat_id'] ?? 0),
            "custom_group"    => (string)($params['custom_group'] ?? ""),
            "request_content" => (string)($params['request_content'] ?? ""),
            "result_code"     => (int)($params['result_code'] ?? 0),
            "result_content"  => (string)($params['result_content'] ?? ""),
            "is_del"          => (int)($params['is_del'] ?? 0),
            "created_at"      => date("Y-m-d H:i:s"),
        ];
        // 判断可选参数index是否为指定索引，不是则默认当前月份
        if (empty($index) || strpos($index, "im_record_") == false) {
            $index = "im_record_" . date("Y-m");
        }
        if (!(ElasticSearch::instance())->index($index)->checkIndexExists()) {
            Log::info("自动创建索引" . $index);
            self::create_index($index, 1, 1, true);
        }
        $res = (ElasticSearch::instance())->index($index)->data($insertInfo)->isSql($isSql)->saveOne();
        if (!empty($res)) {
            return [
                "code" => 200,
                "msg"  => "添加成功"
            ];
        }
        return ["code" => 500, "msg" => "添加失败,字段类型错误"];
    }
}
